import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { combineLatest } from 'rxjs';
import { AlbumService } from './service/apis/album.service';
import { Category } from './service/apis/types';
import { CategoryService } from './service/business/category.service';

@Component({
  selector: 'axz-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
  readonly prefix = 'xmly';
  /**
   * 当前选择的
   */
  currentCategory?: Category;
  categories: Category[] = [];
  categoryPinyin = '';
  subcategory: string[] = [];
  constructor(private album: AlbumService, private categoryService: CategoryService, private router: Router, private ref: ChangeDetectorRef) {

  }

  /**
   * 点击后切换颜色
   * @param category 选中项 （有声书）
   */
  changeCategory(category: Category):void {
    if (this.currentCategory?.id !== category.id) {
      this.currentCategory = category
      this.categoryService.setCategory(category.pinyin)
      this.router.navigateByUrl('/albums/'+category.pinyin)
    }
  }

  private setCurrentCategory(): void {
    this.currentCategory = this.categories.find(item => item.pinyin === this.categoryPinyin);
  }

  private getCategories(): void {
    this.album.categories().subscribe((categories: any) => {
      this.categories = categories;
      this.setCurrentCategory();
      this.ref.markForCheck();
    });
  }
  inIt(): void {
    combineLatest(
      this.categoryService.getCategory(),
      this.categoryService.getSubCategory()
    ).subscribe(([category, subCategories]) => {
      console.log('get category', category);
      if (category !== this.categoryPinyin) {
        this.categoryPinyin = category;
      }
      this.subcategory = subCategories;
    })
    if (this.categories.length) {
      this.setCurrentCategory();
    } else {
      this.getCategories();
    }
   // this.getCategories();
   /*  this.categoryService.getCategory().subscribe((category: any) => {
      // 判断有没有初始化值
      if (category !== this.categoryPinyin) {
        this.categoryPinyin = category
        if (this.categories.length) {
          this.setCurrentCategory();
        } else {
          // 没有则返回youshengshu
          this.getCategories();
        }
      }
      // OnPush策略下不会自动检测变更api
      // this.ref.markForCheck();
    }) */
  }
  ngOnInit(): void {
    this.inIt()
  }
}
